<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>WebSocket Chat</title>
</head>
<body>
<div>
  <label for="userName">User Name: </label>
  <input type="text" id="userName"/>
  <button onclick="join()">Join</button>
</div>

<div>
  <textarea id="chatLog" rows="10" cols="50" readonly></textarea>
</div>

<div>
  <input type="text" id="chatText"/>
  <button onclick="send()">Send</button>
</div>

<script>
  const ws = new WebSocket('ws://localhost:8081/chat');

  ws.onmessage = event => {
    const message = JSON.parse(event.data);
    const type = message.type;
    const groupId = message.groupId;
    const userName = message.userName;
    const text = message.text;

    switch (type) {
      case 'join':
        appendMessage(`[${groupId}][${userName}] joined the chat room.\n`);
        break;
      case 'chat':
        appendMessage(`[${groupId}][${userName}]: ${text}\n`);
        break;
      case 'leave':
        appendMessage(`[${groupId}][${userName}] left the chat room.\n`);
        break;
    }
  };

  function join() {
    const userName = document.getElementById('userName').value;

    const message = {
      type: 'join',
      userName: userName,
      groupId:1
    };

    ws.send(JSON.stringify(message));
  }

  function send() {
    const text = document.getElementById('chatText').value;

    const message = {
      type: 'chat',
      text: text,
      groupId:1
    };

    ws.send(JSON.stringify(message));
  }

  function appendMessage(message) {
    const chatLog = document.getElementById('chatLog');
    chatLog.value += message;
  }
</script>
</body>
</html>